local chengxian = fk.CreateSkill {
  name = "chengxian",
}
local function getTargetsNum(player, card)
  if player:prohibitUse(card) or not player:canUse(card) then return 0 end
  if card.skill:getMinTargetNum() == 0 and not card.multiple_targets then
    return 1
  else
    local x = 0
    for _, p in ipairs(Fk:currentRoom().alive_players) do
      if not player:isProhibited(p, card) and card.skill:modTargetFilter(p, {}, player, card, true) then
        x = x + 1
      end
    end
    return x
  end
end
chengxian:addEffect("viewas", {
  prompt = "#chengxian-active",
  interaction = function()
    local mark = Self:getTableMark("chengxian-turn")
    local all_names = U.getAllCardNames("t")
    local handcards = Self:getCardIds(Player.Hand)
    local names = table.filter(all_names, function(name)
      return not table.contains(mark, Fk:cloneCard(name).trueName) and table.find(handcards, function (id)
        local to_use = Fk:cloneCard(name)
        to_use:addSubcard(id)
        to_use.skillName = "chengxian"
        local x = getTargetsNum(Self, to_use)
        return x > 0 and x == getTargetsNum(Self, Fk:getCardById(id))
      end)~=nil
    end)
    if #names > 0 then
      return U.CardNameBox { choices = names, all_choices = all_names }
    end
  end,
  times =function (self, player)
    if player.phase == Player.Play then
      return  2 + player:getMark("chengxian_extratimes-phase") - player:usedSkillTimes(self.name, Player.HistoryPhase)
    end
    return -1
  end,
  enabled_at_play = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) < 2 + player:getMark("chengxian_extratimes-phase")
  end,
  card_filter =function (self, player, to_select, selected)
    if self.interaction.data == nil or #selected > 0 or Fk:currentRoom():getCardArea(to_select) == Player.Equip then return false end
    local to_use = Fk:cloneCard(self.interaction.data)
    to_use:addSubcard(to_select)
    to_use.skillName = self.name
    return getTargetsNum(player, to_use) == getTargetsNum(player, Fk:getCardById(to_select))
  end,
  view_as = function(self, cards)
    if #cards ~= 1 or not self.interaction.data then return nil end
    local card = Fk:cloneCard(self.interaction.data)
    card:addSubcard(cards[1])
    card.skillName = self.name
    return card
  end,
  before_use = function(self, player, use)
    player.room:addTableMark(player, "chengxian-turn", use.card.trueName)
  end,
})

return chengxian